package mi.payment.constants;

import android.text.TextUtils;

import java.util.HashMap;
import java.util.Map;

import mi.payment.MyApplication;
import mi.payment.R;

/**
 * 各个渠道都存在的errorCode放在Base，特性放在各个渠道下，通过重写moreErrorCode方法
 */
public class BaseErrorCode {

    public static String getCode(String code) {
        return getCode(code, null);
    }

    public static String getCode(String code, String tradeResultDes) {
        if (instance == null) instance = new ErrorCode();
        if (!TextUtils.isEmpty(tradeResultDes)) return tradeResultDes + "(" + code + ")";
        String errorMsg = instance.errorCode.get(code);
        return (errorMsg != null ? errorMsg : getString(R.string.errorOhers)) + "(" + code + ")";
    }

    private static BaseErrorCode instance;

    protected BaseErrorCode() {
        add(KeyValueSet);
        add(moreErrorCode());
    }

    protected Object[] moreErrorCode() {
        return null;
    }

    protected void add(Object[] KeyValueSet) {
        if (KeyValueSet == null) return;
        int size = KeyValueSet.length;
        if (size % 2 == 0)
            for (int i = 0; i < size; i += 2)
                errorCode.put((String) KeyValueSet[i], getString((Integer) KeyValueSet[i + 1]));
        else throw new RuntimeException("Error code key value pairs must be even numbers");
    }

    private Map<String, String> errorCode = new HashMap<>();

    private static String getString(int id) {
        return MyApplication.getInstance().getString(id);
    }

    private static final Object[] KeyValueSet = {
            "00", R.string.error00,
            "38", R.string.error38,
            "51", R.string.error51,
            "61", R.string.error61,
            "68", R.string.error68,
            "75", R.string.error75,
            "A7", R.string.errorA7,
            "E1", R.string.errorE1,
            "E2", R.string.errorE2,
            "E3", R.string.errorE3,
            "E4", R.string.errorE4,
            "F11", R.string.errorF11,
            "F8", R.string.errorF8,
            "NE", R.string.download_nonet,
            "NTR", R.string.NoneTransactionRecord,
            "N1", R.string.error_tmk_download_fail,
            "N2", R.string.terminal_params_download_failed,
            "N3", R.string.params_check_failed,
            "N4", R.string.sign_failed
    };

}
